﻿using ProtoBuf.Message;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEngine.UI;
using Yunchang.NetworkLayer;
using Table.Blo;
using UI;
using Yunchang;
using AutoChess;

public class ChessSandShopPage : OPPage
{
    public class ChessMapInfo
    {
        public int mapId;
        public int sceneClientId;
        public bool isUnlock = false;
        public bool isUsed = false;
        public bool isMonthCardUse = false;
        public int unlockItemId;
        public string mapName = string.Empty;

        public Table.DataModel.TableAutoChessMapShop mapData;
        public ChessMapInfo(Table.DataModel.TableAutoChessMapShop data)
        {
            mapId = data.mapId;
            sceneClientId = data.sceneClientId;
            isMonthCardUse = data.type == 2;
            unlockItemId = data.itemId;
            mapData = data;
            mapName = AutoChessBlo.GetMapNameByChessMapId(mapId); 
        }
    }

    public TextureKit bgTexture;
    public Text useBtnText;
    public GameObject itemRoot,itemPrefab,leftArr, rightArr;
    public ScrollRect scrollRect;

    private List<ChessMapInfo> chessMapInfo = new List<ChessMapInfo>();
    private Dictionary<int, SandItem> mapItem = new Dictionary<int, SandItem>();
    private ChessMapInfo curSelectMap;

    private void Update()
    {
        if (chessMapInfo != null)
        {
            if (chessMapInfo.Count > 4)
                UICommonMethod.UpdateScrollerArrows(scrollRect, leftArr, rightArr, false);
        }
    }

    protected override void DoOpen()
    {
        base.DoOpen();
        GetLocalChessInfo();
        RegisterNet();
        RequrestMapInfo();
    }

    public override void NotifyCoverPageRemove()
    {
        RequrestMapInfo();
    }

    private void RequrestMapInfo()
    {
        NetworkDriver.Instance.SendSocketBlock(OpDefine.CSAutoChessGetMapShopInfo, new CSAutoChessGetMapShopInfo(), OpDefine.SCAutoChessGetMapShopInfo);
    }

    protected override void DoClose(bool immediately)
    {
        base.DoClose(immediately);
        UnregisterNet();
    }

    private void RegisterNet()
    {
        NetworkDriver.Instance.RegistSocketHandler(OpDefine.SCAutoChessGetMapShopInfo, OnSCAutoChessGetMapShopInfo);
        NetworkDriver.Instance.RegistSocketHandler(OpDefine.SCAutoChessUseMap, OnSCAutoChessUseMap);
    }
    private void UnregisterNet()
    {
        NetworkDriver.Instance.UnregisterSocketHandler(OpDefine.SCAutoChessGetMapShopInfo, OnSCAutoChessGetMapShopInfo);
        NetworkDriver.Instance.UnregisterSocketHandler(OpDefine.SCAutoChessUseMap, OnSCAutoChessUseMap);
    }

    private void OnSCAutoChessGetMapShopInfo(object msg)
    {
        var data = msg as SCAutoChessGetMapShopInfo;
        for (int i = 0; i < data.mapInfos.Count; i++)
        {
            var serverData = data.mapInfos[i];
            var temp =  chessMapInfo.Find((a) => { return a.mapId == data.mapInfos[i].mapId; });
            if (temp != null)
            {
                temp.isUnlock = serverData.isActived; 
                temp.isUsed = false;
            }
        }
        var used = chessMapInfo.Find((a) => { return a.mapId == data.usedMapId; });
        used.isUsed = true;

        CreateMapItem();
    }

    private void CreateMapItem()
    {
        for (int i = 0; i < chessMapInfo.Count; i++)
        {
            GameObject tempObject = null;
            var tempData = chessMapInfo[i];
            if (!mapItem.ContainsKey(tempData.mapId))
            {
                tempObject = Instantiate(itemPrefab, itemRoot.transform);
                tempObject.SetActive(true);
            }
            else
            {
                tempObject = mapItem[tempData.mapId].gameObject;
            }
            var script = tempObject.GetComponent<SandItem>();
            script.InitSand(tempData, OnSandItemClick);
            if (curSelectMap == null)
            {
                if (tempData.isUsed)
                {
                    curSelectMap = tempData;
                }
            }

            mapItem[tempData.mapId] = script;
        }
        CheckSelecttedMapItem();
    }

    private void CheckSelecttedMapItem()
    {
        if (curSelectMap != null)
        {
            mapItem[curSelectMap.mapId].SelectedToggle();
        }
        else
        {
            foreach (var item in mapItem)
            {
                if (item.Value.IsUsed())
                {
                    item.Value.SelectedToggle();
                }
            }
        }

        AutoChessManager.Ins.cacheData.MainPageMapId = curSelectMap.mapId;

        SetButtonState();
    }

    private void OnSandItemClick(ChessMapInfo mapInfo)
    {
        curSelectMap = mapInfo;
        bgTexture.TextureName = mapInfo.mapData.bgTexture;
        SetButtonState();
    }

    private void SetButtonState()
    {
        OnTriggerButtonState(
            () => { useBtnText.text = TableTextBlo.GetText("ChessSandUseed"); },
            () => { useBtnText.text = TableTextBlo.GetText("ChessSandUse"); },
            () => { useBtnText.text = TableTextBlo.GetText("ChessSandUnluck"); });
    }

    private void OnSCAutoChessUseMap(object msg)
    {
        var data = msg as SCAutoChessUseMap;
        RequrestMapInfo();
    }

    private void OnTriggerButtonState(Action onMapUsed,Action onMapUnlocked,Action onMaplocked)
    {
        if (curSelectMap.isUsed)
        {
            if(onMapUsed!=null)
                onMapUsed();
        }
        else if (curSelectMap.isUnlock)
        {
            if (onMapUnlocked != null)
                onMapUnlocked();
        }
        else
        {
            if (onMaplocked != null)
                onMaplocked();
        }
    }

    public void OnClickUseButtom()
    {
        OnTriggerButtonState(null, SendUseMapToServer, ToUnlockMap);
    }

    private void SendUseMapToServer()
    {
        NetworkDriver.Instance.SendSocketBlock(OpDefine.CSAutoChessUseMap,
            new CSAutoChessUseMap() { mapId = curSelectMap.mapId },
            OpDefine.SCAutoChessUseMap);
    }

    private void ToUnlockMap()
    {
        if (curSelectMap.isMonthCardUse)//月卡
        {
            PageManager.Instance.OpenPage("ChessCitationPage");
        }
        else //道具
        {
           var itemCell = StaticData.bagData.GetBagCell(BagType.CUSTOM_ITEM_BAG,curSelectMap.unlockItemId, ItemBaseType.ITEM);
            if (itemCell==null || itemCell.Count <= 0)
            {
                MessageBoxManager.Instance.CreatePopupWordTip(
                   string.Format( TableTextBlo.GetText("ChessMapNolockMapItem") , 
                   BagLogic.Instance.GetBagInfo().GetCellName(curSelectMap.unlockItemId,(int)ItemBaseType.ITEM)));
            }
            else
            {
                BagLogic.Instance.SendUseCellMessage((int)itemCell.bagType, itemCell.Index, 1, new List<string>(), 
                    (obj) => 
                    {
                        var scUseMsg = obj as SCUseItem;
                        MessageBoxManager.Instance.CreatePopupWordTip(
                            string.Format(TableTextBlo.GetText("ChessMaplockMapItemSuccess"),curSelectMap.mapName));
                        RequrestMapInfo();
                    });
            }
        }
    }

    private void GetLocalChessInfo()
    {
        chessMapInfo = AutoChessBlo.GetAllMapInfo();
    }
}
